package com.datastructure.test.mergearray;

public class MergeArray {

    public static void main(String[] args) {
        MergeArray mergeArray = new MergeArray();
        int[] a = new int[1];
        int[] b = {1};
        mergeArray.merge(a,0,b,1);
    }

    public void merge(int A[], int m, int B[], int n) {
        if(n==0){
            return;
        }
        if(m==0){
            System.arraycopy(B, 0, A, 0, B.length);
            return;
        }
        int [] temp = new int[m+n];
        int i = 0;
        int j = 0;
        int index = 0;
        while (i<m&&j<n){
            if(A[i]>B[j]){
                temp[index]=B[j];
                index++;
                j++;
            } else if(A[i]<B[j]){
                temp[index]=A[i];
                index++;
                i++;
            } else {
                temp[index]=A[i];
                temp[index+1]=B[j];
                index+=2;
                i++;
                j++;
            }
        }
        if(i==m){
            for(int k =index;k<m+n;k++){
                if(j<n){
                    temp[k]=B[j];
                    j++;
                }
            }
        }
        if(j==n){
            for(int k =index;k<m+n;k++){
                if(i<m){
                    temp[k]=A[i];
                    i++;
                }
            }
        }
        System.arraycopy(temp, 0, A, 0, temp.length);
        System.out.println(A);
    }
}
